import fs from "fs";
import path from "path";
import ejs from "ejs";
import _ from 'lodash';
// import ProgressBar from 'progress'
// const total = languages.length+1;
// // 创建一个进度条对象
// const bar = new ProgressBar('文件结构创建中 [:bar] :percent :etas 当前处理: :description', {
//   total,
// });

class Cebounce {
  ready:boolean;
  timer:any;
  time:number;
  resolve:any;
  code:string;
  constructor(time=500){
    this.ready=false;
    this.timer=null;
    this.time=time;
    
  }
  LastGet(code){
    this.code=code;
    return new Promise(resolve=>{
      this.resolve=resolve
    })
  }
  await(){
    if(this.timer) clearTimeout(this.timer);
    this.timer=setTimeout(() => {
      this.resolve&&this.resolve(this.code)
    }, this.time);

  }
}
interface Params { 
  path: string,
  languages: Array<string>,
  IndexFile: string,
  language: string,
  config_path:string
}
  
interface Key {
  [key:string]:string|number
}
type Keys=Array<Key>



/**
 * 初始化目录文件结构
 * @param {object} params 语种
 */
export class InitStructure {
  filetree:string;
  params:Params;
  DefaultLanguageFilePath:string;//默认语言文件地址
  AddInputFileData:any
  Cebounce:Cebounce
  SetInputChange:any
  constructor(params:Params){
    this.params=params;
    this.filetree=path.join(this.params.path,'modules')
    
    let config:any=fs.readFileSync(this.params.config_path).toString();
    config=JSON.parse(config);
    this.DefaultLanguageFilePath=path.join(this.filetree,config.language+'.json')

    this.initTree();
    this.initFiles();
    this.initInput();
    this.inteData();
  }
  //初始化目录
  initTree(){
    if (!fs.existsSync(this.filetree))
      fs.mkdirSync(this.filetree, { recursive: true });
  }
  //同步主文件 
  initInput(){
    let filePath=this.getIndexPath();
    fs.access(filePath,fs.constants.F_OK,err=>{
      // 文件存在退出程序
      if(!err) return;
      let indexjs = ejs.render(this.params.IndexFile, {
        language:this.params.language,
      });
      fs.writeFileSync(filePath,indexjs)
    })
  }
  //同步data.js 模板数据
  inteData(){
    let outPutfilePath=path.join(__dirname,'../../', "data.json")
    let imports={};
     this.params.languages.forEach(language => {
      imports[language]=`./modules/${language}.json`
     })

    fs.writeFileSync(outPutfilePath,JSON.stringify(imports,null,2))


  }
  getIndexPath(){
    return path.join(this.filetree,'../', "index.js")
  }

  /**
   * 获取keys
   * @returns {object} 语言key
   */
  getKeys(){
      try{
        let  DefaultLanguageFile=fs.readFileSync(this.DefaultLanguageFilePath).toString();
        return JSON.parse(DefaultLanguageFile);
        
      }catch(err){
        return {}
      }
  }
  /**
   * 写入语言包key
   */
  writeKey(language, key:Key|Keys){
    let filePath=path.join(this.filetree,language+'.json').toString();
    let data=JSON.parse(filePath)
    let list:Keys=((typeof key == 'string')?[key]:key) as Keys
    list.forEach((item:Key)=>{
      for(var key in item){
        data[key]=item[key]
      }
    })
    return WriteFile(filePath,JSON.stringify(data))
  }
  initFiles(){
    // 创建各语言仓库
    return this.params.languages.map((name) => 
      WriteFile(this.filetree, name + ".json", "{}",false)
    );
  }
}
/**
 * 文件写入fWriteFile
 * @param filPath  文件路径
 * @param fileName  文件名
 * @param content 文件内容 文件内容为空是 文件名将当做内容写入
 * @param cover 是否覆盖内容
 */
export async function WriteFile(
  filPath: string,
  fileName: string,
  content?: string,
  cover: boolean=true
) {
  let jsonPath = path.join(filPath, content?fileName:'');
  if(cover)
    fs.writeFileSync(jsonPath,content||fileName);
  else 
    fs.access(jsonPath,fs.constants.F_OK,err=>{
      // 文件不存在时才写入
      if(err) 
        fs.writeFileSync(jsonPath,content||fileName);
    })
}

/**
 * JSON修改
 * @param filPath  文件路径
 * @param fileName  文件名
 * @param content 文件内容
 * @param replace 是否强制创建新文件
 */
export async function ModifyJSON(filPath: string, params: any) {
  try {
    let json = JSON.parse(fs.readFileSync(filPath).toString());
    for (var key in params) {
      json[key] = params[key];
    }
    fs.writeFileSync(filPath, JSON.stringify(json, null, 2));
  } catch (e) {
    throw Error("配置文件更新失败");
  }
}

export function deleteFolderSync(folderPath: string) {
  if (fs.existsSync(folderPath)) {
    fs.readdirSync(folderPath).forEach((file) => {
      const curPath = `${folderPath}/${file}`;
      if (fs.lstatSync(curPath).isDirectory()) {
        // 如果是目录，递归删除
        deleteFolderSync(curPath);
      } else {
        // 如果是文件，直接删除
        fs.unlinkSync(curPath);
      }
    });
    fs.rmdirSync(folderPath);
  }
}
